package com.congee02.dbservlet.dao;

import com.congee02.dbservlet.db.SingletonJdbcTemplate;
import com.congee02.dbservlet.entity.User;
import com.congee02.dbservlet.framework.ioc.annotation.Component;
import com.congee02.dbservlet.framework.jdbc.JdbcTemplate;
import com.congee02.dbservlet.framework.jdbc.ObjectJdbcTemplate;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Component
public class UserDao {

    private final ObjectJdbcTemplate<User> userObjectJdbcTemplate =
            ObjectJdbcTemplate.createObjectJdbcTemplate(User.class, SingletonJdbcTemplate.get());

    public int insert(User... user) throws SQLException {
        return userObjectJdbcTemplate.insert(user);
    }

    public int delete(User... conditions) throws SQLException {
        return userObjectJdbcTemplate.delete(conditions);
    }

    public int update(User entity, User... conditions) throws SQLException {
        return userObjectJdbcTemplate.update(entity, conditions);
    }

    public List<User> select(User... conditions) throws SQLException {
        return userObjectJdbcTemplate.select(conditions);
    }

    public boolean isUserExist(String username, String pwd, JdbcTemplate template) throws SQLException {
        boolean result;
        try (PreparedStatement statement = template.createPreparedStatement("SELECT COUNT(0) FROM user2 WHERE username=? AND pwd=?", username, pwd)) {
            ResultSet rs = template.executeQuery(statement);
            rs.next();
            int count = rs.getInt(1);
            result = count >= 1;
        }
        return result;
    }

    public boolean isUserExist(String username, JdbcTemplate template) throws SQLException {
        boolean result;
        try (PreparedStatement statement = template.createPreparedStatement("SELECT COUNT(0) FROM user2 WHERE username=?", username)) {
            ResultSet rs = template.executeQuery(statement);
            rs.next();
            int count = rs.getInt(1);
            result = count >= 1;
        }
        return result;
    }

}
